
import numpy as np


def softmax(x):
    if x.ndim == 2: # 判断是否为二维数组
        x -= np.max(x,axis=1,keepdims=True) # 二维的情况下，行内元素减去行最大值
        x = np.exp(x) # 计算指数
        x /= np.sum(x,axis=1,keepdims=True) # 归一化
    elif x.ndim == 1: # 判断输入是否为一维数组
        x -= x.max() # 一维情况下，整体减去最大值
        x = np.exp(x)/np.sum(np.exp(x)) # 计算指数并归一化
        
    return x 

def cross_entropy_error(y,t):
    if y.ndim == 1:
        t = t.reshape(1,t.size) 
        y = y.reshape(1,y.size)

    if t.size == y.size: # 判断t是否为one-hot向量
        t = t.argmax(axis=1)
    
    batch_size = y.shape[0]
    ret = -np.sum(np.log(y[np.arange(batch_size),t]+1e-7))/batch_size
    return ret 

      
if __name__ == '__main__':
    t = np.array([2,2])
    y = np.array([[0.1,0.05,0.6,0.0,0.05,0.1,0.0,0.1,0.0,0.0],[0.1,0.05,0.1,0.0,0.05,0.1,0.0,0.6,0.0,0.0]])
    cross_entropy_error(y,t)
